/**
 * 标签自动识别
 *
 * @param input 输入的内容
 * @returns
 */
export function parseText(input: string): { think: string; content: string; error: string } {
  const thinkBuf: string[] = []
  const errorBuf: string[] = []
  const contentBuf: string[] = []

  // 当前状态，默认为 content
  let state: 'content' | 'think' | 'error' = 'content'

  // 占位：标签长度常量
  const OPEN_THINK = '<think>'
  const CLOSE_THINK = '</think>'
  const OPEN_ERROR = '<error>'
  const CLOSE_ERROR = '</error>'

  let i = 0
  const len = input.length

  while (i < len) {
    // 检测并切换到 think 区段
    if (input.startsWith(OPEN_THINK, i)) {
      state = 'think'
      i += OPEN_THINK.length
      continue
    }
    // 检测并退出 think 区段
    if (input.startsWith(CLOSE_THINK, i)) {
      state = 'content'
      i += CLOSE_THINK.length
      continue
    }
    // 检测并切换到 error 区段
    if (input.startsWith(OPEN_ERROR, i)) {
      state = 'error'
      i += OPEN_ERROR.length
      continue
    }
    // 检测并退出 error 区段
    if (input.startsWith(CLOSE_ERROR, i)) {
      state = 'content'
      i += CLOSE_ERROR.length
      continue
    }

    // 普通字符，追加到对应缓冲区
    const ch = input[i++]
    if (state === 'think') {
      thinkBuf.push(ch)
    } else if (state === 'error') {
      errorBuf.push(ch)
    } else {
      contentBuf.push(ch)
    }
  }

  // 合并缓冲区并处理空白-only 情况
  const think = thinkBuf.join('').trim() === '' ? '' : thinkBuf.join('')
  const error = errorBuf.join('').trim() === '' ? '' : errorBuf.join('')
  const content = contentBuf.join('')

  return { think, content, error }
}

/**
 * 生成一个唯一的ID
 *
 * @returns
 */
export const geneUniqueID = (() => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyz-' // 37个可用字符
  const MAX_SEQ = 37 ** 5 - 1 // 5位序列最大可能值（37^5=69343957）
  let lastTimeHash = ''
  let sequence = 0

  // 时间戳转36进制哈希（9位）
  function getTimeHash(timestamp: number): string {
    return timestamp.toString(36).slice(-9).padStart(9, '0')
  }

  // 序列转自定义编码（5位，包含-）
  function encodeSequence(seq: number): string {
    let result = ''
    for (let i = 0; i < 5; i++) {
      result = chars[seq % 37] + result
      seq = Math.floor(seq / 37)
    }
    return result
  }

  return function (): string {
    const now = Date.now()
    const currentTimeHash = getTimeHash(now)

    // 新时间片重置序列
    if (currentTimeHash !== lastTimeHash) {
      sequence = 0
      lastTimeHash = currentTimeHash
    }

    // 序列溢出处理（单时间片可生成约6934万不同值）
    if (sequence > MAX_SEQ) {
      throw new Error(`Sequence exhausted for current time slice (limit ${MAX_SEQ + 1})`)
    }

    // 生成5位序列编码
    const seqCode = encodeSequence(sequence)
    sequence++

    // 组合为16位字符串（9位时间哈希 + 5位序列 + 2位校验）
    const checksum = (currentTimeHash.charCodeAt(0) + seqCode.charCodeAt(0)) % 37
    return `${currentTimeHash}${seqCode}${chars[checksum]}`.slice(0, 16)
  }
})()

/**
 * 判断附件是否图片
 *
 * @param attach 附件
 * @returns
 */
export const isImage = (attach: AttachFile) => {
  // 处理非字符串输入或空字符串
  if (typeof attach.mime !== 'string' || attach.mime.trim() === '') {
    return false
  }
  // 图片MIME类型通常以"image/"开头
  return attach.mime.startsWith('image/')
}
